package com.syt.cellphone.information.ui.phone.details

import android.app.Application
import android.content.Intent
import androidx.lifecycle.MutableLiveData
import com.syt.cellphone.information.base.BaseViewModel
import com.syt.cellphone.information.data.pojo.PhoneDetails
import com.syt.cellphone.information.http.RequestHelp
import com.syt.cellphone.information.http.doFailure
import com.syt.cellphone.information.http.doSuccess
import kotlinx.coroutines.flow.collectLatest

/**
 *  @author: syt
 *  创建时间: 2020/9/3 10:03
 *  @功能   手机详情vm
 *  @version v1.0
 */
class PhoneDetailsViewModel(application: Application) : BaseViewModel(application) {

    private var phoneId = ""
    // 数据
    val phoneDetails = MutableLiveData<PhoneDetails>()

    /**
     * 加载数据
     */
    fun initData(intent: Intent) {
        execute {
            phoneId = intent.getStringExtra("phoneId") ?: ""
            RequestHelp
                .getPhoneDetailsById(phoneId)
                .collectLatest { value ->
                    value.doSuccess {
                        phoneDetails.postValue(it)
                    }
                    value.doFailure {
                        toast(it)
                    }
                }

        }
    }

}
